package com.liujun.spring4.demo.aop.ioc.base.beanFactory;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.testng.annotations.Test;

/**
 * 工厂初始化类的信息
 *
 * @author liujun
 * @version 1.0
 * @date 2018-08-12 07:27:00
 */
public class BeanFactoryTest {

  @Test
  public void getBean() throws Throwable {
    // 使用通过路径匹配加载文件
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource res =
        resolver.getResource("classpath:com/liujun/spring4/demo/ioc/base/beanFactory/beans.xml");
    System.out.println(res.getURL());

    DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
    reader.loadBeanDefinitions(res);

    System.out.println("init BeanFactory.");

    Car car = factory.getBean("car", Car.class);
    System.out.println("car bean is ready for use");
    System.out.println(car.toString());
  }

  @Test
  public void getBeanClassPathXml() throws Throwable {
    // 对于ClassPathXmlApplicationContext来说，"com/smart/context/beans.xml"等同于"classpath:com/smart/context/beans.xml"
    ApplicationContext ctx =
        new ClassPathXmlApplicationContext(
                "com/liujun/spring4/demo/aop/ioc/base/beanFactory/beans.xml");
    Car car = (Car) ctx.getBean("car");
    System.out.println("getBeanClassPathXml:" + car);
  }

  @Test
  public void getBeanFileSystemXml() throws Throwable {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource res = resolver.getResource("com/liujun/spring4/demo/aop/ioc/base/beanFactory/beans.xml");

    System.out.println("load path:" + res.getURL());

    //对于FileSystemXmlApplicationContext来说,com/smart/context/beans.xml等同于file:com/smart/context/beans.xml
    ApplicationContext ctx = new FileSystemXmlApplicationContext(res.getURL().getPath());
    Car car = (Car) ctx.getBean("car");
    System.out.println("getBeanFileSystemXml:" + car);
  }
}
